﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Drawing;
using System.Windows.Forms;
using YJTShiftManagement.Events;
using YJTShiftManagement.Models;
using YJTShiftManagement.Service;
using YJTShiftManagement.Utils;

namespace YJTShiftManagement
{
    public partial class LoginForm : UIForm
    {
        private bool m_IsShowPassword = false;          // 是否显示password
        public LoginForm()
        {
            InitializeComponent();

        }
        private void exitPanel_Click(object sender, EventArgs e)
        {
            try
            {
                this.DialogResult = DialogResult.Cancel;
            }
            catch (Exception)
            {
                return;
            }
        }

        private void pic_ShowPwd_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_IsShowPassword)
                {
                    pic_ShowPwd.Image = Properties.Resources.显示;
                    m_IsShowPassword = false;
                    TxtPassWord.PasswordChar = '*';
                }
                else
                {
                    pic_ShowPwd.Image = Properties.Resources.隐藏;
                    m_IsShowPassword = true;
                    TxtPassWord.PasswordChar = default(char);
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void cbRemember_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    this.BtnLoginClick();
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            this.BtnLoginClick();
        }

        private void BtnLoginClick()
        {
            this.BtnLogin.Enabled = false;
            try
            {
                var username = TxtUserName.Text.Trim();
                var password = TxtPassWord.Text.Trim();
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    this.ShowErrorDialog("请填写用户名或者密码!");
                    //MessageBox.Show("请填写用户名或者密码!");
                    this.BtnLogin.Enabled = true;
                    return;
                }
                var loginRequest = new
                {
                    username,
                    password,
                    client = "zm_hospital"
                };


                var result = BaseService.HttpService("api_back/api_login/login", loginRequest);
                if (result.status == "success" && null != result.data && false == string.IsNullOrEmpty(result.data.ToString()))
                {
                    if (result.data != null)
                    {
                        try
                        {
                            // 解析JSON报文
                            var json = JObject.Parse(result.data.ToString());

                            // 检查msg字段是否存在且非空
                            if (json.TryGetValue("info", StringComparison.OrdinalIgnoreCase, out var msgToken)
                                && !string.IsNullOrWhiteSpace(msgToken?.ToString()))
                            {
                                if (this.ShowAskDialog2($"消息内容：{msgToken}", true))
                                {

                                }
                                else
                                {
                                    return;
                                }
                                // 判断点击结果
                                var setResult = BaseService.HttpService("api_back/api_login/login_set_data", loginRequest);
                                if (setResult.status == "success" && null != setResult.data && false == string.IsNullOrEmpty(setResult.data.ToString()))
                                {
                                    var jsons = JObject.Parse(setResult.data.ToString());
                                    if (jsons.TryGetValue("manager_id", StringComparison.OrdinalIgnoreCase, out var manager_id) && !string.IsNullOrWhiteSpace(manager_id?.ToString()))
                                        GlobalApp.Manager_Id = manager_id.ToString();
                                    if (jsons.TryGetValue("token", StringComparison.OrdinalIgnoreCase, out var token) && !string.IsNullOrWhiteSpace(token?.ToString()))

                                        GlobalApp.Token = token.ToString();
                                }
                                else
                                {
                                    this.ShowErrorDialog(result.msg);
                                    if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                                    return;
                                }
                            }
                            else
                            {
                                var setResult = BaseService.HttpService("api_back/api_login/login_set_data", loginRequest);
                                if (setResult.status == "success" && null != setResult.data && false == string.IsNullOrEmpty(setResult.data.ToString()))
                                {
                                    var jsons = JObject.Parse(setResult.data.ToString());
                                    if (jsons.TryGetValue("manager_id", StringComparison.OrdinalIgnoreCase, out var manager_id) && !string.IsNullOrWhiteSpace(manager_id?.ToString()))
                                        GlobalApp.Manager_Id = manager_id.ToString();
                                    if (jsons.TryGetValue("token", StringComparison.OrdinalIgnoreCase, out var token) && !string.IsNullOrWhiteSpace(token?.ToString()))

                                        GlobalApp.Token = token.ToString();
                                }
                                else
                                {
                                    this.ShowErrorDialog(result.msg);
                                    if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                                    return;
                                }
                            }
                        }
                        catch (JsonReaderException ex)
                        {
                            Console.WriteLine($"JSON解析失败：{ex.Message}");
                            DebugFile.IfWrite($"无效的JSON格式报文：{result.data}");
                        }
                    }
                    User user = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(result.data + "");

                    if (user != null)
                    {
                        GlobalApp.GlobalUser = user;

                        GlobalApp.GlobalUser.username = TxtUserName.Text.Trim();
                        GlobalApp.GlobalUser.password = TxtPassWord.Text.Trim();

                        if (this.cbRemember.Checked)
                        {
                            Common.UpdateSettingString("username", GlobalApp.GlobalUser.username);
                            Common.UpdateSettingString("password", GlobalApp.GlobalUser.password);
                            Common.UpdateSettingString("isRemember", "1");
                            //Properties.Settings.Default
                        }
                        else
                        {
                            Common.UpdateSettingString("username", string.Empty);
                            Common.UpdateSettingString("password", string.Empty);
                            Common.UpdateSettingString("isRemember", "0");
                        }

                        this.DialogResult = DialogResult.OK;
                    }
                }
                else
                {
                    this.ShowErrorDialog(result.msg);
                    this.BtnLogin.Enabled = true;
                    if (result.msg.Contains("认证失败")) { EventManager.Instance.RaiseStringEvent("登录界面"); }
                    return;
                }
            }
            catch (Exception)
            {

            }
            this.BtnLogin.Enabled = true;
        }
        private void LoginForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;


                this.lblVerson.Text = "Ver " + Application.ProductVersion.ToString();

                if (Service.BaseService.baseUrl.IndexOf("dvp") > -1)
                {
                    this.lblVerson.Text += "dvp";
                }
                else if (Service.BaseService.baseUrl.IndexOf("testyjt") > -1)
                {
                    this.lblVerson.Text += "testyjt";
                }

                if (Common.GetSettingString("isRemember") == "1")
                {
                    this.cbRemember.Checked = true;
                    this.TxtUserName.Text = Common.GetSettingString("username");
                    this.TxtPassWord.Text = Common.GetSettingString("password");
                }
                else
                {
                    this.cbRemember.Checked = false;
                    this.TxtUserName.Text = string.Empty;
                    this.TxtPassWord.Text = string.Empty;
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void LoginForm_Activated(object sender, EventArgs e)
        {
            try
            {
                TxtUserName.Focus();
            }
            catch (Exception)
            {
                return;
            }
        }

        private void TxtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    this.BtnLoginClick();
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        private void TxtPassWord_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    this.BtnLoginClick();
                }
            }
            catch (Exception)
            {
                return;
            }
        }

        #region "窗口移动代码"
        private bool mIsMouseDown = false;
        private Point mFormLocation;     // Form的location
        private Point mMouseOffset;      // 鼠标的按下位置

        private void OnFormMouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mIsMouseDown = true;
                mFormLocation = this.Location;
                mMouseOffset = Control.MousePosition;
            }
        }

        private void OnFormMouseUp(object sender, MouseEventArgs e)
        {
            mIsMouseDown = false;
        }

        private void OnFormMouseMove(object sender, MouseEventArgs e)
        {
            if (mIsMouseDown)
            {
                Point pt = Control.MousePosition;
                int x = mMouseOffset.X - pt.X;
                int y = mMouseOffset.Y - pt.Y;

                this.Location = new Point(mFormLocation.X - x, mFormLocation.Y - y);
            }
        }

        #endregion

    }
}
